package net.stogi.dsper.ui.client;

import java.util.HashMap;
import java.util.Map;

import net.stogi.common.gwt.frame.client.core.AbstractLayoutManager;

import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.util.Theme;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.HBoxLayout;
import com.extjs.gxt.ui.client.widget.layout.BoxLayout.BoxLayoutPack;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class DsperUiLayoutManagerImpl extends AbstractLayoutManager {

	private final LayoutContainer mainContainer;

	private final Map<String, LayoutContainer> sectionMap;

	public DsperUiLayoutManagerImpl() {
		mainContainer = new LayoutContainer(new BorderLayout());
		sectionMap = new HashMap<String, LayoutContainer>();
		initSections();
	}

	@Override
	public void addWidget(String section, Widget widget) {
		LayoutContainer container = sectionMap.get(section);

		if (container != null) {
			container.add(widget);
		}
		else {
			GWT.log("LayoutManager.addWidget(): No section with given name is defined: [section = '" + section + "']", null);
		}
	}

	@Override
	public void layout() {
		RootPanel.get().remove(mainContainer);
		RootPanel.get().add(mainContainer);
	}

	@Override
	protected void initSections() {
		GXT.setDefaultTheme(Theme.GRAY, true);
		// Layout containers.
		HBoxLayout northLayout = new HBoxLayout();
		northLayout.setPack(BoxLayoutPack.END);

		LayoutContainer north = new LayoutContainer(northLayout);
		BorderLayoutData northData = new BorderLayoutData(LayoutRegion.NORTH, 38);
		northData.setMargins(new Margins(5, 5, 0, 5));
		sectionMap.put("north", north);

		LayoutContainer west = new LayoutContainer();
		BorderLayoutData westData = new BorderLayoutData(LayoutRegion.WEST, .12f);
		westData.setMargins(new Margins(5, 5, 5, 5));
		sectionMap.put("west", west);

		LayoutContainer center = new LayoutContainer();
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER, .60f);
		centerData.setMargins(new Margins(5, 5, 5, 0));
		sectionMap.put("center", center);

		LayoutContainer east = new LayoutContainer();
		BorderLayoutData eastData = new BorderLayoutData(LayoutRegion.EAST, .28f);
		eastData.setMargins(new Margins(5, 5, 5, 0));
		sectionMap.put("east", east);

		mainContainer.add(north, northData);
		mainContainer.add(west, westData);
		mainContainer.add(center, centerData);
		mainContainer.add(east, eastData);
	}
}
